package net.stuffrepos.bricknetcenter.database;

import java.util.Map;
import java.util.TreeMap;
import org.hibernate.Query;
import org.hibernate.Session;

/**
 *
 * @author Eduardo H. Bogoni <eduardobogoni@gmail.com>
 */
public class QueryData {

    private final String hql;
    private Map<String, Object> parameters = new TreeMap<String, Object>();
    private Integer start;
    private Integer limit;

    public QueryData(String hql) {
        this.hql = hql;
    }

    public String getHql() {
        return this.hql;
    }

    public Map<String, Object> getParameters() {
        return parameters;
    }

    public QueryData setParameter(String name, Object value) {
        parameters.put(name, value);
        return this;
    }

    public Query hibernateQuery(Session session) {
        Query query = session.createQuery(getHql());

        for (Map.Entry<String, Object> e : parameters.entrySet()) {
            query.setParameter(e.getKey(), e.getValue());
        }

        if (limit != null) {
            query.setMaxResults(limit);
        }

        if (start != null) {
            query.setFirstResult(start);
        }

        return query;
    }

    public QueryData copyParameters(String hql) {
        QueryData query = new QueryData(hql);
        for (Map.Entry<String, Object> e : parameters.entrySet()) {
            query.setParameter(e.getKey(), e.getValue());
        }
        return query;

    }

    public QueryData paginate(int pageIndex, int pageSize) {
        QueryData query = copyParameters(hql);
        query.setStart(pageIndex * pageSize);
        query.setLimit(pageSize);
        return query;
    }

    private void setStart(Integer start) {
        this.start = start;
    }

    private void setLimit(Integer limit) {
        this.limit = limit;
    }
}
